package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"io/ioutil"
	"net/http"
	"strings"
	"tone-agent/core"
	"tone-agent/entity"
)

func IndexController(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", gin.H{})
}

func LoginController(c *gin.Context) {
	body, _ := ioutil.ReadAll(c.Request.Body)
	data := make(map[string]string)
	json.Unmarshal(body, &data)
	password := strings.Trim(data["password"], " ")
	configAuthPassword := viper.Get(entity.AuthPassword)
	if configAuthPassword == nil || configAuthPassword == "" {
		configAuthPassword = viper.GetString(entity.TSNConfigKey)
	}
	if password == configAuthPassword {
		session := sessions.Default(c)
		session.Set("password", password)
		session.Save()
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "ok",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 201,
			"msg":  "password error",
		})
	}

}

func ConfigController(c *gin.Context) {
	session := sessions.Default(c)
	password := session.Get("password")
	if password == viper.Get(entity.AuthPassword) {
		c.HTML(http.StatusOK, "config.html", gin.H{
			"mode":  viper.Get("mode"),
			"tsn":   viper.Get("tsn"),
			"proxy": viper.Get("proxy"),
		})
	} else {
		c.HTML(http.StatusOK, "login.html", gin.H{})
	}
}

func SetAgentConfig(c *gin.Context) {
	if !viper.GetBool(entity.AllowModifyThroughPageKey) {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg": fmt.Sprintf(
				"Can't modify through the page. Please modify the %s/%s.%s file",
				entity.ConfigPath, entity.APPName, entity.ConfigType,
			),
		})
	} else {
		body, _ := ioutil.ReadAll(c.Request.Body)
		data := make(map[string]string)
		json.Unmarshal(body, &data)
		mode := strings.Trim(data[entity.ModeConfigKey], " ")
		tsn := strings.Trim(data[entity.TSNConfigKey], " ")
		proxy := strings.Trim(strings.Trim(data[entity.ProxyConfigKey], " "), "/")

		err := core.UpdateConfig(tsn, mode, proxy)
		msg := entity.ResponseOk
		if err != nil {
			msg = err.Error()
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  msg,
			"data": gin.H{
				entity.ModeConfigKey:  viper.Get(entity.ModeConfigKey),
				entity.TSNConfigKey:   viper.Get(entity.TSNConfigKey),
				entity.ProxyConfigKey: viper.Get(entity.ProxyConfigKey),
			},
		})
	}
}
